package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.ICompanyService;
import redis.clients.jedis.Jedis;

/**
 * 服务逻辑层，调用数据实现层
 * 1.判断缓存里面是否有数据
 * 2.如果有，则将数据取出并封装到CompanyModel
 * 3.如果没有，则直接从数据库里面取数据
 * 在springboot的时候，redis可以直接存放object和list
 * tomcat 能接受的访问量  300到一千之间
 */
public class CompanyServiceImpl implements ICompanyService {
    @Override
    public CompanyModel getCompanyModelForHome() {
        final CompanyModel[] companyModel = {new CompanyModel()};
        for (int i = 0; i < 500; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    companyModel[0] = setModel();
                }
            }, "线程" + i).start();
        }
        return companyModel[0];
    }

    private CompanyModel setModel() {
        CompanyModel companyModel = new CompanyModel();
//先判断当前缓存是否有数据
        Jedis jedis = new Jedis();//创建jedis的对象，用于取得方法
        Boolean logo = jedis.exists("logo");
        if (logo) {
            //取缓存
            companyModel.setLogo(jedis.get("logo"));
            companyModel.setPhone(jedis.get("phone"));
            companyModel.setNet(jedis.get("net"));
            companyModel.setEmail(jedis.get("email"));
            companyModel.setLinePhone(jedis.get("linePhone"));
            companyModel.setAddress(jedis.get("address"));
            companyModel.setVersion(jedis.get("version"));
            System.out.println("redis");
        } else {
//            要想缓存里面有数据，必须先存入缓存

            CompanyDao companyDao = new CompanyImpl();
            companyModel = companyDao.getCompanyModelForHome();

            jedis.set("logo", companyModel.getLogo());
//            jedis.setex("logo",10,companyModel.getLogo());
            jedis.set("phone", companyModel.getPhone());
            jedis.set("net", companyModel.getNet());
            jedis.set("email", companyModel.getEmail());
            jedis.set("linePhone", companyModel.getLinePhone());
            jedis.set("address", companyModel.getAddress());
            jedis.set("version", companyModel.getVersion());
            System.out.println("mysql");
        }
        return companyModel;
    }

    /**
     * 修改
     *
     * @param companyModel
     * @return
     */
    public int update(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.update(companyModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("logo");
        }
        return result;
    }

    public int del(int id) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.del(id);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("logo");
        }
        return result;
    }
}
